<template>
  <div class="grid_gadget_tempalte" :id="id">
    <Portal
      to="right-disable"
      v-loading="loading"
      :disabled="!queryModelDefaultSetting.showSetting"
    >
      <DashboardInterceptConsumer
        :gadgetId="id"
        shadow="never"
        class="aui-card--fill"
        @mouseenter="mouseenter(true)"
        @mouseleave="mouseenter(false)"
        :style="{ height: gadgetHeight + heightoffset - 35 + 'px', border: 0 }"
      >
        <el-card
          shadow="never"
          class="aui-card--fill content-card"
          :style="{
            height: gadgetHeight + heightoffset - 35 + 'px',
            border: 0,
            overflow: isHasData ? 'visible' : 'hidden'
          }"
        >
          <div>
            <div
              class="cardHeader"
              @mouseenter="mouseenter(true)"
              @mouseleave="mouseenter(false)"
              v-if="
                (widgetName && widgetName.trim().length > 0) ||
                (gadgetSetting.headerDescription &&
                  gadgetSetting.headerDescription.trim().length > 0)
              "
            >
              <GadgetTitle
                :gadgetSetting="gadgetSetting"
                :widgetName="widgetName"
              ></GadgetTitle>
              <div>
                <MoreMenu
                  :slicer="slicer"
                  :fitToHeight="fitToHeight"
                  :gadgetId="id"
                  :gadgetType="gadgetInfo.com"
                  @updateQuery="query"
                  :widgetName="widgetName"
                  :businessType="gadgetInfo.businessType"
                  :id="gadgetInfo.id"
                  @showQueryModel="showQueryModel"
                  @fullScreen="fullScreen"
                />
              </div>
            </div>
            <div class="control-section" style="margin: 10px 10px">
              <!-- <el-button @click="devSetting">get setting</el-button> -->
              <div class="content-wrapper">
                <ejs-pivotview
                  v-if="isHasData"
                  :dataSourceSettings="gadgetSetting.dataSourceSettings"
                  width="100%"
                  :style="{ height: 120 + 'px' }"
                  :height="gadgetHeight - 80"
                  :allowDrillThrough="gadgetSetting.allowDrillThrough"
                  :showTooltip="gadgetSetting.showTooltip"
                  :showFieldList="gadgetSetting.showFieldList"
                  :load="load"
                  :allowExcelExport="gadgetSetting.allowExcelExport"
                  :allowConditionalFormatting="
                    gadgetSetting.allowConditionalFormatting
                  "
                  :allowNumberFormatting="gadgetSetting.allowNumberFormatting"
                  :allowPdfExport="gadgetSetting.allowPdfExport"
                  :showToolbar="gadgetSetting.showToolbar"
                  :allowCalculatedField="gadgetSetting.allowCalculatedField"
                  :toolbar="toolbarItem"
                  :toolbarRender="beforeToolbarRender"
                  :beforeExport="beforeExport"
                  :displayOption="{ view: 'Both' }"
                  :saveReport="saveReport"
                  :enableVirtualization="true"
                  :allowDeferLayoutUpdate="true"
                  :pageSettings="{
                    pageSize: 20
                  }"
                  :showGroupingBar="gadgetSetting.showGroupingBar"
                  :chartSettings="gadgetSetting.chartSettings"
                  :enableValueSorting="gadgetSetting.enableValueSorting"
                  ref="pivotviewgadget"
                >
                </ejs-pivotview>
                <div v-else class="gadget-no-newdata">
                  <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <!-- <div class="widgets-tip"> <a :href="widgetNoDataWiki"
                         :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div> -->
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
        <Lastupdatetime
          v-if="currentTime"
          :currentTime="currentTime"
          :linkedDatasetList="linkedDatasetList"
          :errorStatus="errorStatus"
          @updateQuery="query()"
        ></Lastupdatetime>
      </DashboardInterceptConsumer>
    </Portal>
    <model
      :showSetting="queryModelDefaultSetting.showSetting"
      @queryModelClosed="queryModelClosed"
      @queryModelPreview="queryModelPreview"
      :dataInfo="queryModelDefaultSetting.dataInfo"
      :updateGadget="upgradeGadgetSetting"
    />
    <ExportOptionDialog
      :exportOptionDialogVisible="exportOptionDialogVisible"
      @closeExportOptionDialog="closeExportOptionDialog"
      @confirmExport="confirmExport"
    ></ExportOptionDialog>
  </div>
</template>

<script>
import Vue from 'vue'
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import { defaultGadgetSettingList } from '@/utils/data-json'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'
import { GlobalTimeformat, GlobalDateformat } from '@/utils/common'

import { v4 } from 'uuid'
import ExportOptionDialog from '@/components/export-option-dialog/dialog.vue'
export default {
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: {
    Lastupdatetime,
    model: () => import('@/components/gadget/query-model/query-model'),
    ExportOptionDialog
  },
  data() {
    return {
      currentTime: null,
      isGridInit: false,
      dataList: [],
      loading: false,
      heightoffset: 60,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'pvtablegadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, {
            gadgetType: 'pvtablegadget'
          }).gadgetSetting
        }
      },
      widgetName: '',
      gadgetSetting: {},
      toolbarItem: [
        'Grid',
        'Chart',
        'Export',
        'SubTotal',
        'GrandTotal',
        'Formatting',
        'FieldList'
      ],
      linkedDatasetList: [],
      uuid: v4(),
      exportOptionDialogVisible: false
    }
  },

  beforeCreate() {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  created() {
    this.heightoffset = 5
    this.gadgetHeight = this.pageFrom === 'reportLayoutFullScreen' ? window.screen.availHeight-100 :
    this.pageFromType === 'report'
      ? this.gadgetInfo.h * this.rolHeight - this.heightoffset + 40
      : this.pageFrom === 'reportLayout'
      ? this.gadgetInfo.h * 20 - this.heightoffset + 40
      : this.gadgetInfo.h * 23 - this.heightoffset + 40
    Vue['_this'] = this
    this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    })
    this.$store.state.isWidget = false
  },
  activated() {
    this.uuid = v4()
  },
  computed: {
    comDataList() {
      var _self = this
      var retdata = _self.dataList
      _self.gadgetSetting.dataSourceSettings.dataSource = retdata
      return retdata
    }
  },
  watch: {
    editMode(val) {
      if (!val) {
        this.saveGadgetSetting()
      } else {
      }
    }
  },
  methods: {
    load() {},
    beforeToolbarRender(args) {
      args.customToolbar.splice(6, 0, {
        type: 'Separator'
      })
      args.customToolbar.splice(9, 0, {
        type: 'Separator'
      })
    },
    getPvGadgetSetting() {
      var _self = this
      if (
        _self.$refs['pivotviewgadget'] &&
        _self.$refs['pivotviewgadget'].ej2Instances
      ) {
        var report = JSON.parse(
          _self.$refs['pivotviewgadget'].ej2Instances.getPersistData()
        )
        if (report.dataSourceSettings.dataSource.length > 0) {
          _self.gadgetSetting.dataSourceSettings = {}
          _self.gadgetSetting.dataSourceSettings = {
            calculatedFieldSettings: report.dataSourceSettings
              .calculatedFieldSettings
              ? report.dataSourceSettings.calculatedFieldSettings
              : [],
            columns: report.dataSourceSettings.columns
              ? report.dataSourceSettings.columns
              : [],
            conditionalFormatSettings: report.dataSourceSettings
              .conditionalFormatSettings
              ? report.dataSourceSettings.conditionalFormatSettings
              : [],
            filters: report.dataSourceSettings.filters
              ? report.dataSourceSettings.filters
              : [],
            groupSettings: report.dataSourceSettings.groupSettings
              ? report.dataSourceSettings.groupSettings
              : [],
            rows: report.dataSourceSettings.rows
              ? report.dataSourceSettings.rows
              : [],
            sortSettings: report.dataSourceSettings.sortSettings
              ? report.dataSourceSettings.sortSettings
              : [],
            valueSortSettings: report.dataSourceSettings.valueSortSettings
              ? report.dataSourceSettings.valueSortSettings
              : [],
            values: report.dataSourceSettings.values
              ? report.dataSourceSettings.values
              : [],
            formatSettings: report.dataSourceSettings.formatSettings
              ? report.dataSourceSettings.formatSettings
              : [],
            showAggregationOnValueField:
              report.dataSourceSettings.showAggregationOnValueField,
            showColumnGrandTotals:
              report.dataSourceSettings.showColumnGrandTotals,
            showColumnSubTotals: report.dataSourceSettings.showColumnSubTotals,
            showGrandTotals: report.dataSourceSettings.showGrandTotals,
            showHeaderWhenEmpty: report.dataSourceSettings.showHeaderWhenEmpty,
            showRowGrandTotals: report.dataSourceSettings.showRowGrandTotals,
            showRowSubTotals: report.dataSourceSettings.showRowSubTotals,
            showSubTotals: report.dataSourceSettings.showSubTotals
          }
        }
        // localStorage.setItem(this.id + '-pvtablegadget', JSON.stringify(params))
      }
      return _self.gadgetSetting
    },
    saveReport() {
      // this.getPvGadgetSetting()
    },
    saveGadgetSetting() {
      // var _self = this
      // var abc = null
      // abc = _self._.merge(_self.gadgetSetting, nowSetting || {})
      //  grid table , save obj  from json obj
      // const params = {
      //   gadgetSetting: {
      //     report: nowSetting
      //   },
      //   gadgetId: this.id
      // }
      // this.$interface.reports.putReportsSettingApi(params).then(({ data: res }) => {
      //   if (res.code !== 0) {
      //     return _self.$message.error(res.msg)
      //   }
      // })
    },
    queryModelClosed() {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    queryModelPreview() {
      this.query()
    },
    showQueryModel() {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized(i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight =
        this.pageFromType === 'report'
          ? newH * this.rolHeight - this.heightoffset + 40
          : newH * 20 - this.heightoffset + 40
      this.gadgetWidth = newWPx
    },
    query(e) {
      if (e !== 'auto') {
        this.loading = true
        this._.merge(
          this.gadgetSetting,
          this.queryModelDefaultSetting.dataInfo.gadgetSetting
        )
      }
      var _self = this
      var obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (
        tempObj['name'] &&
        this.slicer['name'] &&
        tempObj['name'] === this.slicer['name']
      )
        delete this.slicer['name']
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      if (!param.pageId) {
        param.type = 'widget'
      }
      _self.$interface.reports
        .getReportDataInfo(param)
        .then(({ data: res }) => {
          _self.verifyHasData(res)
          if (res.config) {
            if(this._.get(this.dataInfo,'gadgetSetting.dynamic',false)){
              _self.gadgetSetting =  this.dataInfo.gadgetSetting
            }else{
                _self.gadgetSetting = Object.assign(
                  {},
                  _self._.merge(_self.gadgetSetting, res.config)
                )
            }
          }
          if (res.name) {
            _self.widgetName = res.name
          } else if (this.wName) {
            _self.widgetName = this.wName
          } else {
            _self.widgetName = _self.gadgetSetting.headerTitle
          }
          _self.selectFields = res.selectFields
          _self.linkedDatasetList = res.datasetSync
          // process data
          if (res.data && res.data.length > 0 && Array.isArray(res.data)) {
            res.data = JSON.parse(JSON.stringify(res.data))
            let selectFieldsObj = res.selectFields[0]
            let queryIdArr = Array.from(
              new Set(res.selectFields.map(item => item.queryId))
            )
            let selectFieldsArr =
              selectFieldsObj &&
              selectFieldsObj.queryId &&
              res.selectFields.filter(
                item =>
                  item.queryId === selectFieldsObj.queryId &&
                  item.dataType === 'dimension'
              )
            if (
              selectFieldsArr &&
              selectFieldsArr.length >= 1 &&
              queryIdArr.length > 1
            ) {
              selectFieldsArr.forEach((item, index) => {
                _self.dataList = res.data.map(ele => {
                  ele[item.alias] = ele[`dimension${index + 1}`]
                  delete ele[`dimension${index + 1}`]
                  return ele
                })
              })
            } else {
              _self.dataList = res.data
            }
            // _self.dataList = _self.dataList.map(item => {
            //   return Object.keys(item).reduce((result, key) => {
            //     const { businessType, fieldsFormat, showbymonday } =
            //       res.selectFields.find(ii => ii.alias === key) || {}
            //     if (
            //       businessType === 'datetime' &&
            //       item[key] &&
            //       item[key].indexOf('Z') > -1
            //     ) {
            //       result[key] = GlobalTimeformat(item[key], fieldsFormat, showbymonday)
            //     } else if (
            //       businessType === 'date' &&
            //       item[key] &&
            //       item[key].indexOf('Z') > -1
            //     ) {
            //       result[key] = GlobalDateformat(item[key], fieldsFormat, showbymonday)
            //     } else {
            //       result[key] = item[key]
            //     }
            //     return result
            //   }, {})
            // })
            _self.gadgetSetting.dataSourceSettings.dataSource = _self.dataList
            if (_self.gadgetSetting.isEmptyCellsTextContent) {
              _self.gadgetSetting.dataSourceSettings.emptyCellsTextContent = '0'
            }
            this.$nextTick(() => {
              let pivotObj = _self.$refs.pivotviewgadget.ej2Instances

              pivotObj = _self._.merge(pivotObj, _self.gadgetSetting)
              pivotObj.pivotRefresh()
            })
          }

          _self.uuid = v4()
          _self.isGridInit = false
        })
        .catch(error => {
          if (this.wName) {
            this.widgetName = this.wName
          }
          this.isHasData = false
          _self.loading = false
          if (error.response && error.response.status === 504) {
            this.errorStatus = '504'
            this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
          }
        })
        .finally(() => {
          this.currentTime = new Date()
          this.autoRefreshQuery(e)
          this.updateGadgetLoadingStatus(!this.loading)
        })
    },
    destroyed() {
      delete Vue['_this']
    },
    remove() {
      this.close()
      if (this.drop.parentNode) {
        this.drop.parentNode.removeChild(this.drop)
      }
    },
    beforeExport() {
      // if (e['pdfExportProperties']) {
      //   e['pdfExportProperties'].isBlob = true
      //   this.exportOptionDialogVisible = true
      // }
    },
    closeExportOptionDialog() {
      this.exportOptionDialogVisible = false
    },
    confirmExport() {
      // this.$refs.datagrid.pdfExport(options)
    }
  }
}
</script>
<style lang="scss" scoped>
.content-card {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 45%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
</style>
<style scoped>
.grid_gadget_tempalte ::v-deep.e-grid .e-summarycell {
  font-size: 13px;
  background-color: #f6f6f6;
  border-color: #e0e0e0;
  color: rgba(0, 0, 0, 0.54);
  font-weight: normal;
}
.el-card ::v-deep .el-card__body {
  width: 100%;
  height: 100%;
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
}

.header {
  display: flex;
  height: 32px;
  justify-content: space-around;
  text-align: center;
  background: no-repeat;
  background-size: cover;
}

.e-grid ::v-deep .e-filter-popup {
  max-height: 300px !important;
  overflow-y: auto;
}

.e-grid ::v-deep .e-checkboxlist {
  height: auto !important;
  overflow-y: visible !important;
}
</style>
